package org.chatboleh.database;

import java.sql.Connection;
import java.sql.Statement;

import org.chatboleh.exception.EDMException;
import org.hsqldb.Server;

public class ServerManager {
	private static boolean running;
	private static Server server;
	private static Thread serverThread;
	private static String shutdownCommand = "SHUTDOWN";

	public static void startServer() {

		// create new server
		server = new Server();

		if(running){
			System.out.println("Database server already running.");
			return;
		} 
		// start server in its own thread
		serverThread = new Thread(new Runnable() {
			public void run() {
				try {
//					Server.main(new String[]{
//							"-database.0","lookupdb",
//							"-dbname.0","mydb"});
					server.setDatabasePath(0, "C:/Users/caslyn/Desktop/TernChow/Eclipse/HSQLDB/Server/edmdb2");
					server.setDatabaseName(0, "edbdb2");
					server.start();
				} catch (Exception ex) {
					System.out.println(ex);
					ex.printStackTrace();
				}
			}
		});
		System.out.println("Starting Database Server...");
		serverThread.start();
		System.out.println("Database Server started.");

		// delay main thread to give the server time to start up
		try {
			int numberOfSeconds = 1;
			Thread.sleep(numberOfSeconds * 1000);
		} catch (InterruptedException ex) {
			System.out.println(ex);
			ex.printStackTrace();
		}

		running = true;
	}

	public static void stopServer() {

		try {
			// Connect to the database and issue SHUTDOWN
			Connection con = ConnectionFactory.getInstance();
			
//			Connection con = DriverManager.getConnection(
//					"jdbc:hsqldb:hsql://localhost/mydb", "sa", "");
			Statement st = con.createStatement();
			st.executeUpdate(shutdownCommand);
			System.out.println("Stopping Database Server...");
//			server.stop();
		} catch (Exception ex) {
			System.out.println(ex);
			ex.printStackTrace();
		} catch (EDMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// delay to give the server time to shut down
		try {
			int numberOfSeconds = 2;
			// wait for numberOfSeconds
			Thread.sleep(numberOfSeconds * 1000);
			// continue here
			System.out.println("Database Server stopped.");
		} catch (InterruptedException ex) {
			System.out.println(ex);
			ex.printStackTrace();
		}

//		server = null;
		serverThread = null;

		// suggest to the JVM that this might be a good time to garbage collect.
		System.gc();

		running = false;

	}
}
